// pages/goods_classify2/goods_classify2.js
const app = getApp()
const Host = require('../../config').Host
const domamin = require('../../config').domamin
Page({

    /**
     * 页面的初始数据
     */
    data: {
        welcomeLoge: domamin + 'Public/static/loginstyle/img/imgy.png',
        successShow:false,
        classifyIndex:0,
        classify:[],
        outerIndex:0,
        goodsIndex: 0,
        mengShow: false,
        tanShow: false,
        count: 1,//初始选择商品的数量
        standardIndex: -1,//初始选择规格的下标
        scrollTop:0,
        scrollTopList:[],//每个分类节点到顶部的距离
        aside_scrollTop:0,
        classifyTopList: [], //左侧栏每个分类标题到顶部的距离
        allList:[],
        product2:[],
        childId:"",
        is_login: false, //是否登录
        phone: '',
        real_code: '', //初始正确的验证码
        code: '',
        sendStart: false, //是否开始发送验证码
        time: 60, //倒计时
        bindShow:false,
        coupon_bg:'/images/activity-bg-min.png',
        logo_img:'/images/zhongtong.png',
        coupon_list: [],
        mengShow2:false,
        couponShow:false,
        isTakePart:false,//是否参与了领取优惠券包括取消优惠券弹窗
        coupon_id: 0,
        coupon_type:'',
        coupon_discount:'',
        coupon_value:'',
        smsId: 0,
        pid:0,
    },
    close3:function(){
        var that=this;
        that.setData({
            mengShow2: false,
            couponShow: false,
            isTakePart: true,
        })
    },
    //取消优惠券弹窗
    cancelCoupon:function(){
        var that = this;
        if (!that.data.bindShow){
            that.close3();
        }
    },
    //领取优惠券
    getCoupon:function(e){
        var that = this;
     
        if(!that.data.is_login){
            that.setData({
                bindShow:true,
            })
        }else{
          var id = e.currentTarget.id
          var openid = wx.getStorageSync('openid');
          wx.request({
            url: Host + 'Default/drawcoupon',
            data: { openid,"couid":id },
            success: function (res) {
              //console.log(res.data);
              if (res.data.code != 200) {
                wx.showToast({
                  title: res.data.errmsg,
                  icon: 'none'
                })
              } else {
                that.close3();
                wx.showToast({
                    title: '领取成功',
                    icon: 'success'
                })
              }
            },
          })
        } 
    },
    getPhone: function (e) {
        this.setData({
            phone: e.detail.value,
        })
    },
    getCode: function (e) {
        this.setData({
            code: e.detail.value,
        })
    },
    sendCode: function () {
        var that = this;
        var reg = new RegExp(/^1(3|4|5|7|8|9)\d{9}$/);
        if (!reg.exec(that.data.phone)) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none',
            })
        } else {
            that.setData({
                sendStart: true,
            })
            function move() {
                var timer = setInterval(() => {
                    var time = that.data.time;
                    time--;
                    that.setData({
                        time: time,
                    })
                    if (time < 0) {
                        clearInterval(timer);
                        that.setData({
                            time: 60,
                            sendStart: false,
                        })
                    }
                }, 1000)
            }
            move();

            var phone = that.data.phone;
            wx.request({
                url: Host + 'Mine/sendverify',
                data: { phone },
                success: function (res) {
                    //console.log(res.data);
                    if (res.data.code == 400) {
                        wx.showModal({
                            title: '提示',
                            content: '验证码发送失败',
                            showCancel: false,
                        })
                    } else {
                        wx.showModal({
                            title: '提示',
                            content: '验证码发送成功，请注意查看',
                            showCancel: false,
                        })
                        that.setData({
                          real_code: res.data.result,
                          smsId: res.data.smsId
                        })
                    }
                },
            })
        }
    },
    login: function () {
        var that = this;
        var reg = new RegExp(/^1(3|4|5|7|8|9)\d{9}$/);
        if (!that.data.phone) {
            wx.showToast({
                title: '请输入手机号',
                icon: 'none',
            })
        } else if (!reg.exec(that.data.phone)) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none',
            })
        } else if (that.data.code != that.data.real_code) {
            wx.showToast({
                title: '请输入正确的验证码',
                icon: 'none',
            })
        } else {
            var phone = that.data.phone;
            var openid = wx.getStorageSync('openid');
            var smsId = that.data.smsId;
            wx.request({
                url: Host + 'Mine/bindphone',
                data: { openid, phone, smsId },
                method: 'post',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                success: function (res) {
                    if (res.data.code == 200) {
                        that.setData({
                            is_login: true,
                            mengShow: false,
                            bindShow:false,
                        })
                        wx.showToast({
                            title: '登录成功',
                            icon: 'success',
                        })
                        // setTimeout(function () {
                        //     wx.switchTab({
                        //         url: '/pages/index2/index2',
                        //     })
                        // }, 1000)
                    } else {
                        wx.showToast({
                            title: res.data.errmsg,
                            icon: 'none',
                        })
                    }
                },
            })
        }
    },
    //监听商品列表滚动
    scroll:function(e){
        var that = this;
        var scrollTop = e.detail.scrollTop;
        // console.log(scrollTop)
        var scrollTopList=that.data.scrollTopList;
        for (let i=0;i<scrollTopList.length;i++){
            if (i<scrollTopList.length-1){
                if (scrollTop>=scrollTopList[i]&&scrollTop< scrollTopList[i+1]){
                    that.setData({
                        classifyIndex: i
                    })
                    console.log(that.data.classifyIndex)
                }
            }else{
                if (scrollTop >= scrollTopList[i]){
                    that.setData({
                        classifyIndex: i
                    })
                }
            }
           
        }
        that.asideScroll();
    },
    //监听左侧栏滚动当前选中的并且满足条件的分类标题滑动到最上方
    asideScroll:function(){
        var that=this;
        var classifyTopList = that.data.classifyTopList;
        // if (classifyTopList.length >= 8) { }
        if (that.data.classifyIndex > 0 && that.data.classifyIndex <= classifyTopList.length - 7) {
            var aside_scrollTop = classifyTopList[that.data.classifyIndex];
            that.setData({
                aside_scrollTop: aside_scrollTop,
            })
        }
    },
    //选择左侧标题分类
    chooseClassifyIndex:function(e){
        var index=e.currentTarget.dataset.id;
        var that = this;
        var classify=that.data.classify;
        var id = classify[index].id;
        var childId = classify[index].childId;
        var scrollTopList = that.data.scrollTopList; 
        that.setData({
            classifyIndex:index,
            childId: childId,
            scrollTop: scrollTopList[index],
        })
        that.asideScroll();
      
      
        //console.log(id)
        
        //获取商品列表
        // that.goodsList();
    },
    // 选择规格
    chooseStandardIndex: function (e) {
        var index = e.currentTarget.id;
        this.setData({
            standardIndex: index,
        })
    },
    getCount: function (e) {
        this.setData({
            count: e.detail.value,
        })
    },
    del: function () {
        var that = this;
        var count = that.data.count;
        count--;
        if (count < 1) {
            count = 1;
            wx.showToast({
                title: '至少选择一个商品',
                icon: 'none',
            })
        }
        that.setData({
            count: count,
        })
    },
    add: function (e) {
        var that = this;
        var count = that.data.count;
        var buynum = e.currentTarget.dataset.buynum;
        if (count >= buynum) {
            count = buynum;
        } else {
            count++;
        }
        that.setData({
            count: count,
        })
    },
    //获取外层商品分类下标
    getOuterIndex:function(e){
        var index=e.currentTarget.id;
        var that=this;
            that.setData({
            outerIndex:index,
        })
    },
    buyShow: function (e) {
        var that = this;
        if (!that.data.is_login) {
            that.setData({
                bindShow: true,
                mengShow: true,
            })
        } else {
            var index = e.currentTarget.id;

            var allList = that.data.allList;
            var product2 = allList[that.data.outerIndex].product[index];
            that.setData({
                product2: product2,
            })
            wx.showToast({
                title: '加载中',
                icon: 'loading',
                duration: 500,
            })
            setTimeout(function () {
                that.setData({
                    goodsIndex: index,
                    mengShow: true,
                    tanShow: true,
                    isScroll: false,
                })
            }, 500)
        } 
    },
    closeShow: function () {
        this.close();
    },
    close: function () {
        var that = this;
        that.setData({
            mengShow: false,
            tanShow: false,
            bindShow:false,
            count: 1,
            standardIndex: -1,
            isScroll: true,
        })
    },
    close2: function () {
        this.setData({
            searchShow: false,
        })
    },
    addCart: function () {
        var that = this;
        var openid = wx.getStorageSync('openid');
        var allList=that.data.allList; 
        var product = allList[that.data.outerIndex].product;
        var goodsIndex = that.data.goodsIndex;
        var standardIndex = that.data.standardIndex;
        var arr = [];
        var obj = {};
        obj.goods_id = product[that.data.goodsIndex].id;
        obj.standard_id = '0';
        if (product[that.data.goodsIndex].standard.length > 0) {
            if (that.data.standardIndex == -1) {
                wx.showToast({
                    title: '您还没有选择规格',
                    icon: 'none',
                })
            } else {
                obj.standard_id = product[goodsIndex].standard[standardIndex].id;
                obj.goods_count = that.data.count;
                arr.push(obj);
                obj = null;
                wx.request({
                    url: Host + 'Default/addcart',
                    data: { openid, item: JSON.stringify(arr) },
                    method: 'post',
                    header: { 'content-type': 'application/x-www-form-urlencoded' },
                    success: function (res) {
                        if (res.data.code == 200) {
                            that.close();
                            wx.showToast({
                                title: '加入购物车成功',
                                icon: 'success',
                            })
                        } else {
                            wx.showToast({
                                title: res.data.errmsg,
                                icon: 'none',
                            })
                        }
                    },
                })
            }
        } else {
            obj.goods_count = that.data.count;
            arr.push(obj);
            obj = null;
            //console.log(arr)
            wx.request({
                url: Host + 'Default/addcart',
                data: { openid, item: JSON.stringify(arr) },
                method: 'post',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                success: function (res) {
                    if (res.data.code == 200) {
                        that.close();
                        wx.showToast({
                            title: '加入购物车成功',
                            icon: 'success',
                        })
                    } else {
                        wx.showToast({
                            title: res.data.errmsg,
                            icon: 'none',
                        })
                    }
                },
            })
        }
       
    },
    onceBuy: function () {
        var that = this;
        var allList = that.data.allList;
        var product = allList[that.data.outerIndex].product;
        var goodsIndex = that.data.goodsIndex;
        var standardIndex = that.data.standardIndex;
        var arr = [];
        var obj = {};
        obj.goods_id = product[that.data.goodsIndex].id;
        obj.standard_id = '0';
        if (product[goodsIndex].standard.length > 0) {
            if (standardIndex == -1) {
                wx.showToast({
                    title: '您还没有选择规格',
                    icon: 'none',
                })
            } else {
                obj.standard_id = product[goodsIndex].standard[standardIndex].id;
                obj.goods_count = that.data.count;
                arr.push(obj);
                obj = null;
                //console.log(arr)
                wx.setStorageSync('order', arr)
                that.close();
                wx.navigateTo({
                    url: '/pages/order/order',
                })
            }
        } else {
            obj.goods_count = that.data.count;
            arr.push(obj);
            obj = null;
            //console.log(arr)
            wx.setStorageSync('order', arr)
            that.close();
            wx.navigateTo({
                url: '/pages/order/order',
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      var that=this;
      if (options.pid) {
        that.setData({
          pid: options.pid,
        })  
      }   
    },
      

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function (){
        var that = this;
        var openid = wx.getStorageSync('openid');
        var pid = that.data.pid;
        //console.log(pid)

        //首页红包
        wx.request({
          url: Host + 'Default/luckybag',
          data: { openid },
          success: function (res) {
            that.setData({
              coupon_list: res.data.coupon_list,
              isTakePart: res.data.isTakePart,
              coupon_bg: res.data.coupon_bg,
            });
          },
          complete:function(){
            var coupon_list = that.data.coupon_list;
            if (coupon_list.length>0) {
              var idx = Math.floor(Math.random() * coupon_list.length);
              that.setData({
                coupon_id: coupon_list[idx].id,
                coupon_type: coupon_list[idx].type,
                coupon_value: coupon_list[idx].value,
                coupon_discount: coupon_list[idx].discount
              })
            }
            
            if (!that.data.isTakePart) {
              that.setData({
                mengShow2: true,
                couponShow: true,
              })
            }
          }
        })

        //获取绑定信息
        wx.request({
            url: Host + 'Mine/personal',
            data: { openid, pid },
            method: 'post',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            success: function (res) {
                that.setData({
                    is_login: res.data.is_bind,
                });
            },
        })
        //获取分类
        wx.request({
            url: Host + 'Default/category',
            data: {},
            success: function (res) {
                that.setData({
                    classify: res.data.list,
                });
                var childId = 0;
                var classify = that.data.classify;
                var classifyIndex = that.data.classifyIndex;
                classify.forEach(item2 => {
                    if (item2.isChoosed) {
                        childId = item2.childId
                    }
                })
                that.setData({
                    childId: childId,
                });
                //获取商品列表
                that.goodsList();
            }
        })
      
          
      
    
    },
  //获取商品列表
  goodsList: function () {
    var that = this;
    var openid = wx.getStorageSync('openid');
    //var childId = that.data.childId;
    that.setData({
      successShow: false,
    })
    wx.request({
      url: Host + 'Default/goodsList2',
      data: { openid},
      success: function (res) {
        that.setData({
            allList: res.data.list,
            successShow: true,//接收数据成功时展示页面
            aside_scrollTop: 0,
            scrollTop: 0,
            classifyIndex: 0,
        })
          setTimeout(() => {
              //获取左侧栏每个标题分类节点到顶部的高度
              var classify = that.data.classify;
              var classifyTopList = [];
              classify.forEach((item, idx) => {
                  var query = wx.createSelectorQuery();
                  //选择id
                  query.select('#aside' + idx).boundingClientRect()
                  query.exec(function (res) {
                      //取高度
                      classifyTopList.push(res[0].top)
                      // console.log(scrollTopList)
                      that.setData({
                          classifyTopList: classifyTopList,
                      })
                  })
              })

              //获取每个商品分类节点到顶部的高度
              var allList = that.data.allList;
              var scrollTopList = [];
              allList.forEach((item, idx) => {
                  var query = wx.createSelectorQuery();
                  //选择id
                  query.select('#title' + idx).boundingClientRect()
                  query.exec(function (res) {
                      //res就是 所有标签为'#title'+idx的元素的信息 的数组
                      //取高度
                      scrollTopList.push(res[0].top)
                      // console.log(scrollTopList)
                      that.setData({
                          scrollTopList: scrollTopList,
                      })
                  })
              })
          }, 500)
      },
    })

  },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})